package com.flowershop.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.Statement;
import java.util.stream.Collectors;

public class DatabaseInitializer {
    
    public static void initDatabase() {
        try (Connection conn = DBUtil.getConnection()) {
            // 读取SQL文件
            InputStream is = DatabaseInitializer.class.getClassLoader()
                    .getResourceAsStream("db/init.sql");
            if (is == null) {
                throw new RuntimeException("Cannot find init.sql");
            }
            
            String sql = new BufferedReader(new InputStreamReader(is))
                    .lines()
                    .collect(Collectors.joining("\n"));
            
            // 分割SQL语句
            String[] statements = sql.split(";");
            
            // 执行每个SQL语句
            try (Statement stmt = conn.createStatement()) {
                for (String statement : statements) {
                    if (!statement.trim().isEmpty()) {
                        stmt.execute(statement);
                    }
                }
            }
            
            System.out.println("Database initialized successfully!");
        } catch (Exception e) {
            System.err.println("Failed to initialize database: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        // 可以直接运行这个方法来初始化数据库
        initDatabase();
    }
} 